package com.ruoyi.project.pay;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WBRedPackageUtil {
    //发包COOKIE
//    String cookiePayer = "配置成你自己的发包号的cookie;";
//    //拆包COOKIE
//    String cookieSeller = "你自己的拆包号的cookie;";
//    //拆包ID
//    String uidSeller = "拆包的UID";

    /**
     * 获取支付的html
     * 拼手气红包
     * @param money 总金额
     * @param count 红包个数
     */
    public static String getPayUrl(double money, int count, String cookiePayer) {
//        double singalAmount = money / count; // 单个红包金额
        HashMap<String ,String > map = new HashMap<>();
        map.put("X-Requested-With", "XMLHttpRequest");
        map.put("Referer", "https://mall.e.weibo.com/h5/redenvelope/create?page=2");
        map.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1)");
        map.put("Cookie", cookiePayer);

//        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        headers.add("X-Requested-With", "XMLHttpRequest");
//        headers.add("Referer", "https://mall.e.weibo.com/h5/redenvelope/create?page=2");
//        headers.add("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1)");
//        headers.add("Cookie", cookiePayer);
        //拼手气红包 每个红包的金额随机
        String data = "bag_type=0&puicode=0&msgtype=1&msgid=0&amount=" + money + "&count=" + count + "&blessing=快来抢，手快有，手慢无。恭喜发财！&_t=0";
        // String data ="bag_type=1&puicode=0&msgtype=0&msgid=0&singalAmount="+singalAmount+"&amount=" + money + "&count=" + count + "&blessing=快来抢，手快有，手慢无。恭喜发财！&_t=0";
//        HttpEntity entity = new HttpEntity(data, headers);
//        String order = restTemplate.exchange("https://mall.e.weibo.com/aj/redenvelope/create", HttpMethod.POST, entity, String.class).getBody();
        String order = HttpUtils.sendPost3("https://mall.e.weibo.com/aj/redenvelope/create",map,data);
        System.out.println("getPayUrl result:" + order);

        JSONObject objectOrder = JSONObject.parseObject(order);
        String url = objectOrder.getJSONObject("data").getString("url");
        String userAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Mobile Safari/537.36";
        map = new HashMap<>();
        map.put("User-Agent",userAgent);
        map.put("Cookie",cookiePayer);
        String result= HttpUtils.sendGet(url,map,"");
        result = result.replace("<!DOCTYPE HTML><html>\t<head>\t<meta charset=\"utf-8\">\t<title>微博红包</title>\t</head>\t<body>","").replace("<script>\t\tdocument.getElementById('alipayForm').submit();\t</script>\t</body></html>","");
        return result;
    }


    /**
     * 查单
     * 注意！！ 下边参数的 start_time 和 end_time 取值为当天即可
     * @param tradeId
     */
    public static JSONObject checkOrder(String tradeId,String cookiePayer) {
//        Map<String, String> mapPayer = new HashMap<>();
//        mapPayer.put("Cookie", cookiePayer);
//        HttpClient.doPost("https://pay.sc.weibo.com/aj/pc/biz/list",
//                "biz_type=0&status=0&biz_id=" + tradeId + "&start_time=2019-11-30&end_time=2019-11-30&page=1&page_size=10",
//                null,
//                mapPayer);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Cookie", cookiePayer);
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String data ="biz_type=0&status=0&biz_id=" + tradeId + "&start_time="+time+"&end_time="+time+"&page=1&page_size=10";
        HttpEntity entity = new HttpEntity(data, headers);
        String order = restTemplate.exchange("https://pay.sc.weibo.com/aj/pc/biz/list",HttpMethod.POST, entity, String.class).getBody();
        // {"code":"100000","msg":"\u64cd\u4f5c\u6210\u529f","data":{"biz":[{"biz_id":"124443734394395373","uid":"1844081083","biz_type":"2","show_type":"41","trade_uid":"5136362277","subject":"\u5fae\u535a\u7ea2\u5305","has_refund":"0","amount":"2.00","status":"2","biz_time":"2019-11-28 22:45:03","create_time":"2019-11-28 22:45:03","modify_time":"2019-11-28 22:46:54","amount_prefix":"-","trade_user_nickname":"\u5fae\u535a\u7ea2\u5305","trade_user_image":"https:\/\/tva2.sinaimg.cn\/crop.0.0.300.300.50\/005BBEsRjw8fa7nsaun07j308c08cmxa.jpg?KID=imgbed,tva&Expires=1574963245&ssig=7Sc7KUaqQ2","subject_cut":"\u5fae\u535a\u7ea2\u5305","order_id":"6000058223377","pay_time":"2019-11-28 22:46:54","pay_info":{"pay_id":"124443734394395373","out_pay_id":"6000058223377","seller_id":"5136362277","appkey":"743219212","buyer_id":"1844081083","subject":"\u5fae\u535a\u7ea2\u5305","body":"","total_amount":"200","pay_channel":"103","pay_method":"2","charge_id":"174443734394395497","charge_amount":"200","amount_charge":"-200","amount_balance":"0","amount_unsettle":"0","amount_settled":"200","amount_fee":"0","cfg":"{\"cfg_follow_uid\":\"5136362277\",\"cfg_share_opt\":\"0\",\"cfg_follow_opt\":\"0\"}","notify_url":"https:\/\/hb.e.weibo.com\/v2\/bonus\/pay\/wnotify","return_url":"https:\/\/hb.e.weibo.com\/v2\/bonus\/pay\/wreturn?sinainternalbrowser=topnav","expire":"86400","extra":"","status":"1","sub_status":"0","pay_time":"2019-11-28 22:46:54","close_time":"2019-11-29 22:45:03","create_time":"2019-11-28 22:45:03","update_time":"2019-11-28 22:46:59","coupon_amount":"0","amount_coupon":"0"},"biz_type_desc":"\u6d88\u8d39","show_type_desc":"\u7ea2\u5305","status_desc":"\u4ea4\u6613\u6210\u529f"}],"count":0,"page":"1","page_size":"10","has_next_page":false,"notice":false,"notify_msg":false}}
        JSONObject jsonObject = JSONObject.parseObject(order);
        return  jsonObject;
    }


    /**
     * 用户发红包消息给拆红包人
     */
    public static JSONObject sendRedpackage(String orderid,String cookiePayer,String uidSeller) {
//        Map<String, String> mapPayer = new HashMap<>();
//        mapPayer.put("X-Requested-With", "XMLHttpRequest");
//        mapPayer.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1)");
//        mapPayer.put("Cookie", cookiePayer);
//        String order = HttpClient.doPost("https://mall.e.weibo.com/aj/redenvelope/sendmsg",
//                "msgid=" + uidSeller + "&msgtype=1&set_id=" + orderid + "&_t=0",
////                null, mapPayer);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Cookie", cookiePayer);
        headers.add("X-Requested-With", "XMLHttpRequest");
        headers.add("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1)");
        String data = "msgid=" + uidSeller + "&msgtype=1&set_id=" + orderid + "&_t=0";
        HttpEntity entity = new HttpEntity(data, headers);
        String order = restTemplate.exchange("https://mall.e.weibo.com/aj/redenvelope/sendmsg",HttpMethod.POST, entity, String.class).getBody();
        JSONObject jsonObject = JSONObject.parseObject(order);
        return  jsonObject;
    }

    /**
     * 拆包
     */
    public static String pickMoney(String orderid,String cookieSeller) {

        Map<String, String> mapSeller = new HashMap<>();
        mapSeller.put("Cookie", cookieSeller);
        mapSeller.put("x-user-agent", "HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1");
        mapSeller.put("X-Requested-With", "com.sina.weibo");
        mapSeller.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1)");
        String result = HttpUtils.sendGet("https://mall.e.weibo.com/h5/redenvelope/draw?set_id=" + orderid + "&sinainternalbrowser=topnav&portrait_only=1&from=1097295010&weiboauthoruid= ",
                mapSeller,"");
        return result;
    }

    /**
     * 解析出tradeid
     * @param formStr
     * @return
     */
    public static String getTradeId(String formStr){
//        String str ="<form action=\"https://openapi.alipay.com/gateway.do?charset=UTF-8\" method=\"POST\" id=\"alipayForm\">\t<input name=\"app_id\" type=\"hidden\" value=\"2016010401062614\"/>\t<input name=\"method\" type=\"hidden\" value=\"alipay.trade.wap.pay\"/>\t<input name=\"format\" type=\"hidden\" value=\"JSON\"/>\t<input name=\"return_url\" type=\"hidden\" value=\"https://pay.sc.weibo.com/charge/wap/return2\"/>\t<input name=\"charset\" type=\"hidden\" value=\"UTF-8\"/>\t<input name=\"sign_type\" type=\"hidden\" value=\"RSA2\"/>\t<input name=\"timestamp\" type=\"hidden\" value=\"2019-12-02 11:26:15\"/>\t<input name=\"version\" type=\"hidden\" value=\"1.0\"/>\t<input name=\"notify_url\" type=\"hidden\" value=\"https://pay.sc.weibo.com/api/alipay/wap/notify2\"/>\t<input name=\"biz_content\" type=\"hidden\" value=\"{&quot;subject&quot;:&quot;微博红包&quot;,&quot;out_trade_no&quot;:&quot;104445013120164850&quot;,&quot;timeout_express&quot;:1,&quot;total_amount&quot;:&quot;20.00&quot;,&quot;product_code&quot;:&quot;QUICK_WAP_WAY&quot;,&quot;quit_url&quot;:&quot;https:\\/\\/pay.sc.weibo.com\\/pay\\/wap\\/fail?msg=%E6%94%AF%E4%BB%98%E5%BC%82%E5%B8%B8&quot;}\"/>\t<input name=\"sign\" type=\"hidden\" value=\"oFisPsn8qbr+1DY0g/hsKZ7v8T3HYSyCn8VPDgU+JzPUNtemHM9fHrz43l4A+ddG23Ksck503WSlyiZGpDdAIulpAKE0Mkpoolpi0AEwmm3JSXMXgvQhrVUV+u2IQ9YNNVJ0GWu3BWxeW1M+JoxrN/Mxm2U2rhJtbr/vnwqqegUtmaV/w8JHqiFFPXOT6vu9NDsTVjgA1/9sJhfr6GcroE8NyEei3AC9S6A+DNlaK7/pLfCdK7u3siTfg9ZyBMYQq1EFK+T+fq5Qh8kUQRY3dH5ONWbndi2SpRdOlBrQlDwYxEpmMuUyyq9JndCKVIKMUJsDHMSIfSPekrDcgI9/XA==\"/>\t</form>";
        String[] strs = formStr.split("&quot;out_trade_no&quot;:&quot;");
        String[] tradeIds = strs[1].split("&quot;,&quot;timeout_express");
        return tradeIds[0];
    }

    public static String getAmount(String formStr){
//        String str ="<form action=\"https://openapi.alipay.com/gateway.do?charset=UTF-8\" method=\"POST\" id=\"alipayForm\">\t<input name=\"app_id\" type=\"hidden\" value=\"2016010401062614\"/>\t<input name=\"method\" type=\"hidden\" value=\"alipay.trade.wap.pay\"/>\t<input name=\"format\" type=\"hidden\" value=\"JSON\"/>\t<input name=\"return_url\" type=\"hidden\" value=\"https://pay.sc.weibo.com/charge/wap/return2\"/>\t<input name=\"charset\" type=\"hidden\" value=\"UTF-8\"/>\t<input name=\"sign_type\" type=\"hidden\" value=\"RSA2\"/>\t<input name=\"timestamp\" type=\"hidden\" value=\"2019-12-02 11:26:15\"/>\t<input name=\"version\" type=\"hidden\" value=\"1.0\"/>\t<input name=\"notify_url\" type=\"hidden\" value=\"https://pay.sc.weibo.com/api/alipay/wap/notify2\"/>\t<input name=\"biz_content\" type=\"hidden\" value=\"{&quot;subject&quot;:&quot;微博红包&quot;,&quot;out_trade_no&quot;:&quot;104445013120164850&quot;,&quot;timeout_express&quot;:1,&quot;total_amount&quot;:&quot;20.00&quot;,&quot;product_code&quot;:&quot;QUICK_WAP_WAY&quot;,&quot;quit_url&quot;:&quot;https:\\/\\/pay.sc.weibo.com\\/pay\\/wap\\/fail?msg=%E6%94%AF%E4%BB%98%E5%BC%82%E5%B8%B8&quot;}\"/>\t<input name=\"sign\" type=\"hidden\" value=\"oFisPsn8qbr+1DY0g/hsKZ7v8T3HYSyCn8VPDgU+JzPUNtemHM9fHrz43l4A+ddG23Ksck503WSlyiZGpDdAIulpAKE0Mkpoolpi0AEwmm3JSXMXgvQhrVUV+u2IQ9YNNVJ0GWu3BWxeW1M+JoxrN/Mxm2U2rhJtbr/vnwqqegUtmaV/w8JHqiFFPXOT6vu9NDsTVjgA1/9sJhfr6GcroE8NyEei3AC9S6A+DNlaK7/pLfCdK7u3siTfg9ZyBMYQq1EFK+T+fq5Qh8kUQRY3dH5ONWbndi2SpRdOlBrQlDwYxEpmMuUyyq9JndCKVIKMUJsDHMSIfSPekrDcgI9/XA==\"/>\t</form>";
        String[] strs = formStr.split("<p class=\"red_amount\">");
        String[] tradeIds = strs[1].split("</p>  <a href=\"sinaweibo://browser");
        return tradeIds[0];
    }
}
